package com.ikas.ai.server.module.flow.listener;

import com.ikas.ai.framework.core.event.FlowEvent;
import com.ikas.ai.framework.core.listener.FlowListener;
import com.ikas.ai.framework.flow.FlowStatus;
import com.ikas.ai.framework.flow.ScoreFlow;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.server.module.flow.model.FlowInstance;
import com.ikas.ai.server.module.flow.service.FlowInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description: 流程记录机制
 * @Author: qi.yilai
 * @Date: 2023/2/1 13:52
 * @Version: 1.0.0
 **/
@Component
public class MaintainFlowListener implements FlowListener {

    @Lazy
    @Autowired
    private FlowInstanceService flowInstanceService;

    @Override
    public boolean fireEvent(FlowEvent event) {
        ScoreFlow scoreFlow = event.getOwner();

        FlowInstance flowInstance = new FlowInstance();
        flowInstance.setSceneId(scoreFlow.getSceneId());
        flowInstance.setFlowId(scoreFlow.getFlowId());
        flowInstance.setId(scoreFlow.getFlowInstanceId());

        FlowStatus flowStatus = scoreFlow.getStatus();
        flowInstance.setStatus(flowStatus.getStatus().byteValue());

        switch (flowStatus) {
            case STARTING:
                flowInstance.setStartTime(new Date(scoreFlow.getStartTime()));
                flowInstance.setUpdateTime(new Date());
                break;
            case SUCCESS:
            case FAILURE:
            case STOP:
                flowInstance.setEndTime(new Date(scoreFlow.getEndTime()));
                flowInstance.setUpdateTime(new Date());
                break;
            default:
                throw new BusinessException("状态不合法");
       }

        flowInstanceService.updateById(flowInstance);
        return true;
    }
}
